//
//  AppSortViewController.m
//  SouthChina
//
//  Created by kc on 15/8/26.
//  Copyright (c) 2015年 科创. All rights reserved.
//首页应用排序

#import "AppSortViewController.h"
#import "PublicAccount.h"
#import "HomePageController.h"

@interface AppSortViewController ()
{
     long tmptag ;
     long tmptagold ;
}

@property(nonatomic,strong)NSMutableArray * myRects;//存放所有的view
@property(nonatomic,strong)NSMutableArray * frames;//存放view的标准位置

@end

@implementation AppSortViewController
@synthesize APPList;
- (void)viewDidLoad {
    [super viewDidLoad];
     // Do any additional setup after loading the view.
     [self addTitleBarWithBackBtn:@"首页应用排序" needReturn:NO];
    
    //初始化两个数组
    self.myRects = [NSMutableArray arrayWithCapacity:APPList.count];
    self.frames = [NSMutableArray arrayWithCapacity:APPList.count];
    tmptag = -1;
    tmptagold = -1;
    
    //初始化页面
    for (int i = 0; i < APPList.count; i++)
    {
        PublicAccount *publicaccount = [APPList objectAtIndex:i];
        UIView *ViewItme = [[UIView alloc] initWithFrame:CGRectMake(15 + i%4 *75, self.titlebar.frame.origin.y+self.titlebar.frame.size.height+10+ i/4 * 65, 56, 56)];
        ViewItme.backgroundColor = [UIColor clearColor];
        ViewItme.tag = i;
        NSLog(@"初始化序号为:%@",publicaccount.userSort);
        [self.view addSubview:ViewItme];
        
        //图像
        NSURL *url= [NSURL URLWithString: [publicaccount.headImg hasPrefix:@"http"]?publicaccount.headImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,publicaccount.headImg]];
        UIImageView * HeadImg = [[UIImageView alloc] initWithFrame:CGRectMake(7,5, 43, 43)];
        [HeadImg setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        HeadImg.layer.masksToBounds = YES;
        HeadImg.layer.cornerRadius = 8;
        [ViewItme addSubview:HeadImg];
        
        //应用名称
        UILabel *labelName = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 56, 10)];
        labelName.text = publicaccount.appName;
        labelName.textAlignment = NSTextAlignmentCenter;
        labelName.font = [UIFont systemFontOfSize:10.0f];
        labelName.textColor =[UIColor colorWithRed:105.0f/255.0f green:105.0f/255.0f blue:105.0f/255.0f alpha:1.0f];
        [ViewItme addSubview:labelName];
        
        //删除图片
        UIImageView * deletImg = [[UIImageView alloc] initWithFrame:CGRectMake(2,0, 15, 15)];
        deletImg.image = [UIImage imageNamed:@"btn_delete.png"];
        [ViewItme addSubview:deletImg];
        
        [self.myRects addObject:ViewItme];
        NSString * str = [NSString stringWithFormat:@"%@",NSStringFromCGRect(ViewItme.frame)];
        [self.frames addObject:str];
        
        //拖动切换位置
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(dragButton:)];
        [ViewItme addGestureRecognizer:pan];
        
        //响应点击事件
        UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickDeleteApp:)];
        [ViewItme addGestureRecognizer:singleTap];
    }
    
    //标题栏上显示完成按钮
    UIButton *finishBtn = [[UIButton alloc] initWithFrame:CGRectMake(266, self.titlebar.frame.origin.y+20, 50, 40)];
    [finishBtn addTarget:self action:@selector(OnClickedfinishBtn:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [self.titlebar addSubview:finishBtn];

}

//删除某个元素
-(void) onClickDeleteApp:(UITapGestureRecognizer *)sender{
    CGPoint point = [sender locationInView:self.view];
    long selectedtag = -1;
    //判断点在哪个应用点击范围内
    for (int i = 0; i< self.myRects.count; i++)
    {
        UIView *  viewtmp= self.myRects[i];
        NSString* tmprect = self.frames[i];
        
        if (CGRectContainsPoint(CGRectFromString(tmprect), point))
        {
            selectedtag = viewtmp.tag;
            break;
        }
    }
    NSLog(@"删除索引为：%ld",selectedtag);
    //从删除的那个索引开始，后面的前移
    if(selectedtag>=0)
    {
        if(selectedtag<self.myRects.count-1)
        {
            for(long k = selectedtag;k<self.myRects.count-1;k++)
            {
                NSString * rect1 = self.frames[k];
                NSString * rect2 = self.frames[k+1];
                UIView * view1 = self.myRects[k];
                UIView * view2 = self.myRects[k+1];
                
                view1.frame = CGRectFromString(rect2);
                view2.frame = CGRectFromString(rect1);
                
                //并交换其tag值及在数组中得位置
                long tmptag0 = view2.tag;
                view2.tag = view1.tag;
                view1.tag = tmptag0;
                
                [self.myRects exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                [APPList exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                
                if(k==self.myRects.count-2)//最后一个元素
                {
                    UIView * viewlast = self.myRects[k+1];
                    [viewlast removeFromSuperview];
                    //删除最后一个元素
                    [self.myRects removeLastObject];
                    [self.frames removeLastObject];
                    PublicAccount *publicaccount = [APPList objectAtIndex:k+1];
                    publicaccount.isHome = @"0";
                    publicaccount.userSort = @"0";
                }
            }
        }
        else
        {
            UIView * viewlast = self.myRects[self.myRects.count-1];
            [viewlast removeFromSuperview];
            //删除最后一个元素
            PublicAccount *publicaccount = [APPList objectAtIndex:self.myRects.count-1];
            publicaccount.isHome = @"0";
            publicaccount.userSort = @"0";
            
            [self.myRects removeLastObject];
            [self.frames removeLastObject];
        }
    }
   
}

//拖动排序
-(void)dragButton:(UIPanGestureRecognizer*)pan
{
    //获取手势在该视图上得偏移量
    CGPoint translation = [pan translationInView:self.view];
    //一下分别为拖动时的三种状态：开始，变化，结束
    if (pan.state == UIGestureRecognizerStateBegan)
    {
        //开始时拖动的view更改透明度
        pan.view.alpha = 0.7;
        tmptagold = pan.view.tag;
        NSLog(@"开始 %ld",tmptagold);
    }
    else if(pan.state == UIGestureRecognizerStateChanged)
    {
        //使拖动的view跟随手势移动
        pan.view.center = CGPointMake(pan.view.center.x + translation.x,
                                      pan.view.center.y + translation.y);
        [pan setTranslation:CGPointZero inView:self.view];
        
        //遍历9个view看移动到了哪个view区域，使其为选中状态.并更新选中view的tag值，使其永远为最新的
        for (int i = 0; i< self.myRects.count; i++)
        {
            UIView *  viewtmp= self.myRects[i];
            NSString* tmprect = self.frames[i];
            if (CGRectContainsPoint(CGRectFromString(tmprect), pan.view.center))
            {
                tmptag = viewtmp.tag;
                viewtmp.layer.borderWidth = 3;
                viewtmp.layer.borderColor = [[UIColor redColor]CGColor];
                return;
            }
            else
            {
                viewtmp.layer.borderWidth = 0;
                viewtmp.layer.borderColor = [[UIColor clearColor]CGColor];
            }
        }
    }
    else if (pan.state == UIGestureRecognizerStateEnded)
    {
        //拖动结束的时候，将拖动的view的透明度还原
        pan.view.alpha = 1;
        [UIView animateWithDuration:1 animations:^
         {
             //结束时将选中view的边框还原
             NSLog(@"结束时 tmptag：%ld",tmptag);
             UIView * viewtmp = self.myRects[tmptag];
             viewtmp.layer.borderWidth = 0;
             viewtmp.layer.borderColor = [[UIColor clearColor]CGColor];
             if(tmptagold == tmptag)
             {
                 //回到原来位置
                 NSString * rectold = self.frames[tmptagold];
                 pan.view.frame = CGRectFromString(rectold);
             }
             else{
                 //往前移动
                 if(pan.view.tag>tmptag)
                 {
                     for(long k = pan.view.tag-1;k>=tmptag;k--)
                     {
                         NSString * rect1 = self.frames[k];
                         NSString * rect2 = self.frames[k+1];
                         UIView * view1 = self.myRects[k];
                         UIView * view2 = self.myRects[k+1];
                         
                         view2.frame = CGRectFromString(rect1);
                         view1.frame = CGRectFromString(rect2);
                         
                         //并交换其tag值及在数组中得位置
                         view2.tag = k;
                         view1.tag = k+1;
                         
                         [self.myRects exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                         [APPList exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                     }
                 }
                 if(pan.view.tag<tmptag) //往后挪
                 {
                     for(long k = pan.view.tag;k<=tmptag-1;k++)
                     {
                         NSString * rect1 = self.frames[k];
                         NSString * rect2 = self.frames[k+1];
                         UIView * view1 = self.myRects[k];
                         UIView * view2 = self.myRects[k+1];
                         
                         view1.frame = CGRectFromString(rect2);
                         view2.frame = CGRectFromString(rect1);
                         
                         //并交换其tag值及在数组中得位置
                         view2.tag = k;
                         view1.tag = k+1;
                         
                         [self.myRects exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                         [APPList exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                     }
                 }
             }
         } completion:^(BOOL finished)
         {
             //完成动画后还原btn的状态
             for (int i = 0; i< self.myRects.count; i++)
             {
                 UIView * viewtmp = self.myRects[i];
                 viewtmp.layer.borderColor = [[UIColor clearColor]CGColor];
                 viewtmp.layer.borderWidth = 0;
             }
         }];
    }
}

//完成事件
-(void)OnClickedfinishBtn:(id)sender{
    NSLog(@"xxxxxxxx点击完成事件");
    NSMutableArray *appUpdateList = [[NSMutableArray alloc] init];
    //重新排编号
    for(long i = 0;i<APPList.count;i++)
    {
        PublicAccount *publicaccount = [APPList objectAtIndex:i];
        if([publicaccount.isHome isEqualToString:@"1"]) //没有删除的应用重新排序
        {
            publicaccount.userSort = [NSString stringWithFormat:@"%ld",1001+i];
        }
        else
        {
            publicaccount.userSort = @"0";
        }
        NSDictionary *appInfo = @{@"appId":publicaccount.appId,@"sort":publicaccount.userSort,@"isHome":publicaccount.isHome};
        [appUpdateList addObject:appInfo];
    }
   
    int nCnt = appUpdateList.count;
    //调用接口
    NSDictionary *params = @{@"apps":appUpdateList};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"setHomeApps" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            //更新本地库表
            for(long i = 0;i<APPList.count;i++)
            {
                PublicAccount *publicacnt = [APPList objectAtIndex:i];
                [PublicAccountDao updatePublicAccount:publicacnt];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:@"操作成功！"];
        }
        else{
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:@"操作失败！"];
        }
        //返回上一层界面
        kAppDelegate.needRefrsh=YES;
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
